package me.zhengjie.modules.business.rest;

import me.zhengjie.annotation.AnonymousAccess;
import me.zhengjie.aop.log.Log;
import me.zhengjie.modules.business.domain.Question;
import me.zhengjie.modules.business.service.QuestionService;
import me.zhengjie.modules.business.service.WxUserService;
import me.zhengjie.modules.business.service.dto.QuestionDto;
import me.zhengjie.modules.business.service.dto.QuestionQueryCriteria;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
* @author churuitao
* @date 2020-02-02
*/
@Api(tags = "业务：问题管理")
@RestController
@RequestMapping("/api/question")
public class QuestionController {

    private final QuestionService questionService;

    private final WxUserService wxUserService;

    public QuestionController(QuestionService questionService, WxUserService wxUserService) {
        this.questionService = questionService;
        this.wxUserService = wxUserService;
    }

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    //@PreAuthorize("@el.check('question:list')")
    @AnonymousAccess
    public void download(HttpServletResponse response, QuestionQueryCriteria criteria) throws IOException {
        questionService.download(questionService.queryAll(criteria), response);
    }

    @GetMapping
    @Log("查询问题(单表查询，返回集合，通用接口)")
    @ApiOperation("查询问题(单表查询，返回集合，通用接口)")
    @AnonymousAccess
    //@PreAuthorize("@el.check('question:list')")
    public ResponseEntity<Object> getQuestions(QuestionQueryCriteria criteria,@PageableDefault(value = 20, sort = { "id" }, direction = Sort.Direction.DESC) Pageable pageable){
        return new ResponseEntity<>(questionService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    @PostMapping
    @Log("新增问题")
    @ApiOperation("新增问题(需要调用文件上传的接口，返回文件路径)")
    @AnonymousAccess
    //@PreAuthorize("@el.check('question:list')")
    public ResponseEntity<Object> create(@Validated @RequestBody Question resources){
        return new ResponseEntity<>(questionService.create(resources),HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改问题（通用修改方法）")
    @ApiOperation("修改问题（通用修改方法）")
    @AnonymousAccess
    //@PreAuthorize("@el.check('question:list')")
    public ResponseEntity<Object> update(@Validated @RequestBody Question resources){
        questionService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("删除question")
    @ApiOperation("删除question")
    //@PreAuthorize("@el.check('question:del')")
    @DeleteMapping
    @AnonymousAccess
    public ResponseEntity<Object> deleteAll(@RequestBody Integer[] ids) {
        questionService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }
    @Log("查询用户汇总数据")
    @ApiOperation("查询用户汇总数据")
    @GetMapping("/getCount")
    @AnonymousAccess
    public ResponseEntity<Object> countQuestion(Integer id, Integer type) {
        return new ResponseEntity<>(questionService.countQuestion(id, type), HttpStatus.OK);
    }

    @Log("查询一条问题，携带发送方和接收方的信息")
    @ApiOperation("查询一条问题，携带发送方和接收方的信息")
    @AnonymousAccess
    //@PreAuthorize("@el.check('question:list')")
    @GetMapping("/getById")
    public ResponseEntity<QuestionDto> getQuestionById(Integer questionId) {
        return new ResponseEntity<>(questionService.getQuestionById(questionId),HttpStatus.OK);
    }

    @ApiOperation("新增问题（问题图片上传）(暂时有问题，先不用)")
    @Log("新增问题（问题图片上传）")
    @PostMapping(value = "/insert-question-picture")
    @AnonymousAccess
    public ResponseEntity<Object> insertAndPicture(@Validated @RequestBody Question resources,@RequestPart MultipartFile file){
        return new ResponseEntity<>(questionService.insertAndPicture(resources,file),HttpStatus.OK);
    }

    @Log("解答方抢回答问题")
    @ApiOperation("解答方抢回答问题")
    @AnonymousAccess
    @PostMapping("/solve")
    public ResponseEntity<Object> solveQuestion(Integer aid, Integer qid){
        if(wxUserService.checkAuthStatus(aid)){
            if(questionService.rushThisQuestion(qid,aid)){
                return new ResponseEntity<>(HttpStatus.NO_CONTENT);
            }
            return new ResponseEntity<>("这道题已经被别人抢走了，下次记得快点~",HttpStatus.BAD_REQUEST);
        }
        return new ResponseEntity<>("用户身份验证未通过",HttpStatus.BAD_REQUEST);
    }

    @PutMapping("/updateSolving")
    @Log("修改问题状态：解答方解答问题时（正在解答），调整问题状态为1")
    @ApiOperation("修改问题状态：解答方解答问题时（正在解答），调整问题状态为1")
    @AnonymousAccess
    public ResponseEntity<Object>updateSolving(Integer questionId,Integer answerId ){
        questionService.updateSolving(questionId,answerId);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @PutMapping("/updateChatContent")
    @Log("修改问题状态：聊天信息从redis保存到数据库（当结束此次解答时调用），status改为2")
    @ApiOperation("修改问题状态：聊天信息从redis保存到数据库（当结束此次解答时调用），status改为2")
    @AnonymousAccess
    //@PreAuthorize("@el.check('question:list')")
    public ResponseEntity<Object> updateChatContent(Integer questionId,Integer askId,Integer answerId){
        questionService.updateChatContent(questionId,askId,answerId);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @GetMapping("/getChatContent")
    @Log("查询解决问题时的聊天记录（从redis缓存中查询）")
    @ApiOperation("查询解决问题时的聊天记录（从redis缓存中查询）")
    @AnonymousAccess
    //@PreAuthorize("@el.check('question:list')")
    public ResponseEntity<Object> getChatContent(Integer questionId,Integer askId,Integer answerId){
        return new ResponseEntity<>(questionService.getChatContent(questionId,askId,answerId),HttpStatus.OK);
    }

}